/**
 * 权限认证服务
 * 提供用户权限检查和认证相关功能
 */

// 权限常量定义
export const PERMISSIONS = {
  // 任务相关权限
  TASK_VIEW: "task:view",
  TASK_CLAIM: "task:claim",
  TASK_START: "task:start",
  TASK_PAUSE: "task:pause",
  TASK_RESUME: "task:resume",
  TASK_COMPLETE: "task:complete",
  TASK_UPDATE_PROGRESS: "task:update:progress",
  TASK_BATCH_OPERATE: "task:batch:operate",

  // 生产计划相关权限
  PLAN_VIEW: "plan:view",
  PLAN_CREATE: "plan:create",
  PLAN_EDIT: "plan:edit",
  PLAN_DELETE: "plan:delete",
  PLAN_START: "plan:start",
  PLAN_PAUSE: "plan:pause",
  PLAN_COMPLETE: "plan:complete",

  // 工作中心权限
  WORK_CENTER_VIEW: "workCenter:view",
  WORK_CENTER_MANAGE: "workCenter:manage",
};

class AuthService {
  constructor() {
    this.userPermissions = [];
    this.userInfo = null;
    this.init();
  }

  // 初始化权限服务
  init() {
    this.loadUserInfo();
    this.loadUserPermissions();
  }

  // 加载用户信息
  loadUserInfo() {
    try {
      const userInfoStr = uni.getStorageSync("login_user_info");
      if (userInfoStr) {
        // 检查是否已经是对象
        if (typeof userInfoStr === 'object') {
          this.userInfo = userInfoStr;
        } else if (typeof userInfoStr === 'string') {
          // 尝试解析JSON字符串
          this.userInfo = JSON.parse(userInfoStr);
        }
      }
    } catch (error) {
      console.error("加载用户信息失败:", error);
      // 尝试从其他存储键获取用户信息
      this.tryLoadFromAlternativeKeys();
    }
  }

  // 尝试从其他可能的存储键加载用户信息
  tryLoadFromAlternativeKeys() {
    const alternativeKeys = ['userInfo', 'USER_INFO', 'user_info'];
    
    for (const key of alternativeKeys) {
      try {
        const userInfoStr = uni.getStorageSync(key);
        if (userInfoStr) {
          if (typeof userInfoStr === 'object') {
            this.userInfo = userInfoStr;
            console.log(`从 ${key} 成功加载用户信息`);
            return;
          } else if (typeof userInfoStr === 'string') {
            this.userInfo = JSON.parse(userInfoStr);
            console.log(`从 ${key} 成功解析用户信息`);
            return;
          }
        }
      } catch (error) {
        console.warn(`从 ${key} 加载用户信息失败:`, error);
      }
    }
    
    // 如果都失败了，设置默认用户信息
    this.setDefaultUserInfo();
  }

  // 设置默认用户信息（开发阶段）
  setDefaultUserInfo() {
    this.userInfo = {
      id: 'dev_user_001',
      username: 'developer',
      realname: '开发用户',
      workTypeId: 1,
      roles: ['employee']
    };
    console.log('使用默认用户信息');
  }

  // 加载用户权限
  loadUserPermissions() {
    try {
      const permissionsStr = uni.getStorageSync("userPermissions");
      if (permissionsStr) {
        this.userPermissions = JSON.parse(permissionsStr);
      } else {
        // 如果没有权限信息，设置默认权限（开发阶段）
        this.setDefaultPermissions();
      }
    } catch (error) {
      console.error("加载用户权限失败:", error);
      this.setDefaultPermissions();
    }
  }

  // 设置默认权限（开发阶段使用）
  setDefaultPermissions() {
    this.userPermissions = [
      PERMISSIONS.TASK_VIEW,
      PERMISSIONS.TASK_CLAIM,
      PERMISSIONS.TASK_START,
      PERMISSIONS.TASK_PAUSE,
      PERMISSIONS.TASK_RESUME,
      PERMISSIONS.TASK_COMPLETE,
      PERMISSIONS.TASK_UPDATE_PROGRESS,
      PERMISSIONS.TASK_BATCH_OPERATE,
      PERMISSIONS.PLAN_VIEW,
      PERMISSIONS.PLAN_CREATE,
      PERMISSIONS.PLAN_EDIT,
      PERMISSIONS.PLAN_START,
      PERMISSIONS.PLAN_PAUSE,
      PERMISSIONS.WORK_CENTER_VIEW,
    ];
  }

  // 检查单个权限
  hasPermission(permission) {
    if (!permission) return true;
    return this.userPermissions.includes(permission);
  }

  // 检查多个权限（需要全部拥有）
  hasAllPermissions(permissions) {
    if (!permissions || permissions.length === 0) return true;
    return permissions.every((permission) => this.hasPermission(permission));
  }

  // 检查多个权限（拥有其中任意一个即可）
  hasAnyPermission(permissions) {
    if (!permissions || permissions.length === 0) return true;
    return permissions.some((permission) => this.hasPermission(permission));
  }

  // 获取用户信息
  getUserInfo() {
    return this.userInfo;
  }

  // 获取用户ID
  getUserId() {
    return this.userInfo?.id || null;
  }

  // 获取用户名
  getUsername() {
    return this.userInfo?.username || "";
  }

  // 获取用户角色
  getUserRoles() {
    return this.userInfo?.roles || [];
  }

  // 检查是否有指定角色
  hasRole(role) {
    const roles = this.getUserRoles();
    return roles.includes(role);
  }

  // 更新用户权限
  updatePermissions(permissions) {
    this.userPermissions = permissions || [];
    try {
      uni.setStorageSync(
        "userPermissions",
        JSON.stringify(this.userPermissions)
      );
    } catch (error) {
      console.error("保存用户权限失败:", error);
    }
  }

  // 更新用户信息
  updateUserInfo(userInfo) {
    this.userInfo = userInfo;
    try {
      uni.setStorageSync("userInfo", JSON.stringify(userInfo));
    } catch (error) {
      console.error("保存用户信息失败:", error);
    }
  }

  // 清除认证信息
  clearAuth() {
    this.userInfo = null;
    this.userPermissions = [];
    try {
      uni.removeStorageSync("userInfo");
      uni.removeStorageSync("userPermissions");
      uni.removeStorageSync("token");
    } catch (error) {
      console.error("清除认证信息失败:", error);
    }
  }

  // 检查是否已登录
  isAuthenticated() {
    const token = uni.getStorageSync("token");
    return !!(token && this.userInfo);
  }

  // 获取Token
  getToken() {
    return uni.getStorageSync("token") || "";
  }

  // 设置Token
  setToken(token) {
    try {
      uni.setStorageSync("token", token);
    } catch (error) {
      console.error("保存Token失败:", error);
    }
  }

  // 权限检查装饰器（用于方法权限控制）
  requirePermission(permission) {
    return (target, propertyKey, descriptor) => {
      const originalMethod = descriptor.value;
      descriptor.value = function (...args) {
        if (!authService.hasPermission(permission)) {
          uni.showToast({
            title: "权限不足",
            icon: "none",
          });
          return Promise.reject(new Error("权限不足"));
        }
        return originalMethod.apply(this, args);
      };
      return descriptor;
    };
  }

  // 任务操作权限检查方法
  canClaimTask() {
    return this.hasPermission(PERMISSIONS.TASK_CLAIM);
  }

  canStartTask() {
    return this.hasPermission(PERMISSIONS.TASK_START);
  }

  canPauseTask() {
    return this.hasPermission(PERMISSIONS.TASK_PAUSE);
  }

  canResumeTask() {
    return this.hasPermission(PERMISSIONS.TASK_RESUME);
  }

  canCompleteTask() {
    return this.hasPermission(PERMISSIONS.TASK_COMPLETE);
  }

  canUpdateTaskProgress() {
    return this.hasPermission(PERMISSIONS.TASK_UPDATE_PROGRESS);
  }

  canBatchOperateTask() {
    return this.hasPermission(PERMISSIONS.TASK_BATCH_OPERATE);
  }

  // 生产计划权限检查方法
  canCreatePlan() {
    return this.hasPermission(PERMISSIONS.PLAN_CREATE);
  }

  canEditPlan() {
    return this.hasPermission(PERMISSIONS.PLAN_EDIT);
  }

  canStartPlan() {
    return this.hasPermission(PERMISSIONS.PLAN_START);
  }

  canPausePlan() {
    return this.hasPermission(PERMISSIONS.PLAN_PAUSE);
  }
}

// 创建单例实例
const authService = new AuthService();

export default authService;
export { authService };
